<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <el-form-item label="用户名" prop="name">
      <el-input v-model="ruleForm.name" />
    </el-form-item>
    <el-form-item label="密码" prop="name">
      <el-input v-model="ruleForm.pwd" type="password" />
    </el-form-item>
    <el-form-item label="手机号" prop="name">
      <el-input v-model="ruleForm.phone" style="width:200px"/>&nbsp;&nbsp;&nbsp;
      <el-button type="success" @click="sendCode" disabled>获取验证码</el-button>
    </el-form-item>
    <el-form-item label="验证码" prop="name">
      <el-input v-model="ruleForm.code" />
    </el-form-item>
    <el-form-item >
      <el-checkbox v-model="ischeck">
          记住密码
        </el-checkbox>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        Create
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref,onMounted } from 'vue'
import { ElMessage } from 'element-plus';
import { useCounterStore } from '@/stores/counter';
const useStore=useCounterStore();
import { useRouter } from 'vue-router';
const router = useRouter();
import { api1, api2 } from '@/main';
//@ts-ignore
import Cookies from 'js-cookie'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

interface RuleForm {
  name: string
  pwd: string
  phone: string
  code: string
}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  name: '',
  pwd: '',
  phone: '',
  code: ''
})

const locationOptions = ['Home', 'Company', 'School']
const ischeck = ref(false);
const rules = reactive<FormRules<RuleForm>>({})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      api1.post('/api/User/VerifyCode',{
            phone: ruleForm.phone,
            code: ruleForm.code
          })
      .then(res=>{
        console.log(res);
        if(res.data.message.includes('输入验证码正确'))
        {
          ElMessage.success(res.data.message);
            // 返回下一个 Promise（登录请求）
          return api1.get('/api/User/Login',{
            params:{
              UserName: ruleForm.name,
              Password: ruleForm.pwd
           }
          });
        }
        else
        {
          ElMessage.error(res.data.message);
          return Promise.reject(new Error(res.data.message)); // 返回拒绝的 Promise
        }
      })
      .then(res=>{
        if(res.data.isSuc)
        {
          if(ischeck.value)
          {
            Cookies.set('name',ruleForm.name, { expires: 7 });
            Cookies.set('pwd',ruleForm.pwd, { expires: 7 });
          }
          else
          {
            Cookies.remove('name');
            Cookies.remove('pwd');
          }
          window.localStorage.setItem("token", res.data.data.strToken);
        // 数据提交后端要加入新的Token值
        api1.defaults.headers.common["Authorization"] =
            "Bearer " + res.data.data.strToken;
        api2.defaults.headers.common["Authorization"] =
            "Bearer " + res.data.data.strToken;
            useStore.userId=res.data.data.userId;
            useStore.userName=res.data.data.userName;
          ElMessage.success(res.data.msg);
          router.push('/MenuView');
         }
         else
         {
           ElMessage.error(res.data.msg);
         }
      })


    } else {
      console.log('error submit!', fields)
    }
  })
  .catch(error=>{
    console.log(error);
    ElMessage.error(error.message);
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const sendCode = () => {
  api1.post('/api/User/SendSms?phone='+ruleForm.phone)
  .then(res=>{
    console.log(res);
    ElMessage.success(res.data);
  })
}
onMounted(()=>{
  loadUser();
})
const loadUser=()=>{
  var name=Cookies.get('name');
  if(name)
  {
    ruleForm.name=Cookies.get('name');
    ruleForm.pwd=Cookies.get('pwd');
    ischeck.value=true;
    ruleForm.code="1362"
  }
}


</script>
